<template>
  <div class="admin-add-user-page">
    <div class="page-header">
      <h1>添加用户</h1>
    </div>

    <div class="form-container">
      <el-form
        :model="userForm"
        :rules="rules"
        ref="userFormRef"
        label-width="100px"
        class="user-form"
      >
        <el-form-item label="账号" prop="userAccount">
          <el-input v-model="userForm.userAccount" placeholder="请输入账号"></el-input>
        </el-form-item>

        <el-form-item label="用户昵称" prop="userName">
          <el-input v-model="userForm.userName" placeholder="请输入用户昵称"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="userPassword">
          <el-input v-model="userForm.userPassword"  type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        
        <el-form-item label="用户角色" prop="userRole">
          <el-select v-model="userForm.userRole" placeholder="选择角色" clearable>
            <el-option label="普通用户" value="user" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="userForm.gender">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="头像" prop="imageUrl">
          <div class="user-image-uploader">
            <img v-if="userForm.image_url" :src="userForm.imageUrl" class="user-image" />
            <div v-else class="upload-placeholder">
              <FileUpload
                :tip="'支持jpg、png格式，不超过5MB'"
                :max-size="5"
                :validate-file-type="validateImageType"
                @upload-success="handleImageSuccess"
              >
                <el-button type="primary">
                  <el-icon><el-icon-plus /></el-icon>
                  上传头像
                </el-button>
              </FileUpload>
            </div>
          </div>
          <div class="upload-tip">点击上传图片，只能上传jpg/png文件，且不超过5MB</div>
          <div v-if="userForm.image_url" class="change-image">
            <FileUpload
              :tip="'支持jpg、png格式，不超过5MB'"
              :max-size="5"
              :validate-file-type="validateImageType"
              @upload-success="handleImageSuccess"
            >
              <el-button type="primary" size="small">
                更换头像
              </el-button>
            </FileUpload>
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="submitForm">提交</el-button>
          <el-button @click="$router.push('/admin/users')">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { addUserApi } from '../../api/user'
import FileUpload from '../../components/FileUpload.vue'

const userFormRef = ref(null)
const router = useRouter()
const userList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const currentUserId = ref(null)

// 表单数据
const userForm = reactive({
  userAccount:'',
  userName: '',
  userPassword: '',
  userRole: '',
  gender: 0,
  imageUrl: ''
})

// 表单验证规则
const rules = {
  userAccount: [
    { required: true, message: '请输入账号', trigger: 'blur' }
  ],
  userName: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  userPassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  userRole: [
    { required: true, message: '请选择用户角色', trigger: 'change' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  imageUrl: [
    { required: true, message: '请上传头像图片', trigger: 'change' }
  ]
}

// 图片类型校验
const validateImageType = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG 或 PNG 格式!')
    return false
  }
  return true
}

// 图片上传成功的回调
const handleImageSuccess = (response) => {
  userForm.image_url = response
  ElMessage.success('图片上传成功')
}

// 提交表单
const submitForm = () => {
  userFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    loading.value = true
    try {
      await addUserApi(userForm)
      ElMessage.success('添加用户成功')
      router.push('/admin/users')
    } catch (error) {
      console.error('添加用户失败:', error)
      ElMessage.error('添加用户失败')
    } finally {
      loading.value = false
    }
  })
}
</script>

<style scoped>
.admin-add-user-page {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 24px;
  color: #303133;
  margin: 0;
}

.form-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.user-form {
  max-width: 600px;
}

.user-image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.user-image-uploader:hover {
  border-color: #409EFF;
}

.upload-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}

.user-image {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.upload-tip {
  font-size: 12px;
  color: #606266;
  margin-top: 10px;
}

.change-image {
  margin-top: 10px;
}
</style> 